<template>
	<el-dialog
		v-model="treeDialogVisible"
		title="分配权限"
		width="30%"
	>
		<template #header="{ close, titleId, titleClass }">
			<div class="my-header">
				分配权限
				<n-space justify="end">
					<n-checkbox @update:checked="openCloseTreeCheckedChange">
						展开/折叠
					</n-checkbox>
					<n-checkbox @update:checked="allSelOrNoSelTreeCheckChange">
						全选/全不选
					</n-checkbox>
				</n-space>
			</div>
		</template>
		<el-tree
			ref="treeRef"
			:props="props"
			:data="treeData"
			show-checkbox
			node-key="id"
		/>
		<template #footer>
			<n-space justify="end">
				<n-button @click="treeDialogVisible=false">取消</n-button>
				<n-button type="primary" @click="getCheckedNodes">更新</n-button>
			</n-space>
		</template>
	</el-dialog>
</template>

<script setup>
import {reactive, toRefs, ref, onMounted} from "vue";
import {assignmentPermission, getMenuListByRoelId, menuTree} from "@/service";
import {useMessage} from "naive-ui";
const emit=defineEmits(['fetch-data'])
const msg = useMessage()
const treeRef = ref(null);
const state = reactive({
	treeDialogVisible: false,
	treeData: [],
})

const {treeDialogVisible,treeData} = toRefs(state)

const props = {
	label: 'label',
	children: 'children',
}

// 全选全不选
const allSelOrNoSelTreeCheckChange = (checked) => {
	if (checked) {
		treeRef.value.setCheckedNodes(state.treeData)
	} else {
		treeRef.value.setCheckedNodes([])
	}
}
// 展开折叠
const openCloseTreeCheckedChange = (checked) => {
	if (checked) {
		Object.values(treeRef.value.store.nodesMap).forEach((v) => v.expand())
	} else {
		Object.values(treeRef.value.store.nodesMap).forEach((v) => v.collapse())
	}
}

const getTreeAllData = async () => {
	const {data} = await menuTree();
	state.treeData = data;
}
const handlerPermission = async (row) => {
	state.roleId = row.roleId;
	//注意 获取所有树的数据一定要先于 treeRef.value?.setChecked 否则不生效
	// 获取所有树
	await getTreeAllData();
	state.treeDialogVisible = true
	const {data} = await getMenuListByRoelId(row.roleId);
	if (data) {
		data.forEach(item => {
			treeRef.value?.setChecked(item, true, false)
		})

	}
}


// 获取所有选中的节点
const getCheckedNodes = async () => {
	// 第二个参数为true可以获取到半选节点数据
	let checkedNodes = treeRef.value.getCheckedNodes(false, true);
	if (checkedNodes) {
		let permissionIds = checkedNodes.map(item => item.id);
		// 对接后端
		const {data} = await assignmentPermission({"menuIds": permissionIds, "roleId": state.roleId});
		resultTableInit(data);
		state.roleId = '';
		state.treeDialogVisible = false;
	}
}

const resultTableInit = (data) => {
	if (!data) {
		msg.error("处理失败")
	} else {
		msg.success("处理成功");
	}
	emit('fetch-data')
}

defineExpose({
	handlerPermission
})


</script>

<style scoped>

</style>
